import { APIs } from "apis";
import { getToken, setToken, removeToken } from "utils/auth";

const state = {
    token: getToken(),
    userInfo: {},
};

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token;
    },

    SET_USERINFO: (state, userInfo) => {
        state.userInfo = userInfo;
    },
};

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { username, password, identityEnum } = userInfo;
        return new Promise((resolve, reject) => {
            APIs.login({ username: username.trim(), password: password, identityEnum })
                .then(response => {
                    console.log(response);
                    commit("SET_USERINFO", response);
                    resolve();
                })
                .catch(error => {
                    reject(error);
                });
        });
    },

    // get user info
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            APIs.getInfo({ params: { token: state.token } })
                .then(response => {
                    const { data } = response;

                    if (!data) {
                        reject("Verification failed, please Login again.");
                    }

                    const { roles, name, avatar, introduction } = data;

                    // roles must be a non-empty array
                    if (!roles || roles.length <= 0) {
                        reject("getInfo: roles must be a non-null array!");
                    }

                    commit("SET_ROLES", roles);
                    commit("SET_NAME", name);
                    commit("SET_AVATAR", avatar);
                    commit("SET_INTRODUCTION", introduction);
                    resolve(data);
                })
                .catch(error => {
                    reject(error);
                });
        });
    },

    // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            APIs.logout({ params: { token: state.token } })
                .then(() => {
                    commit("SET_TOKEN", "");
                    removeToken();
                    resolve();
                })
                .catch(error => {
                    reject(error);
                });
        });
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit("SET_TOKEN", "");
            removeToken();
            resolve();
        });
    },
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
};
